package com.handler.client;

import com.message.RpcRespMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author 罗俊华
 * @date 2021/9/2 - 9:22 上午
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcRespHandler extends SimpleChannelInboundHandler<RpcRespMessage> {

    private final Map<Integer, Promise<Object>> promiseMap;

    public RpcRespHandler(Map<Integer, Promise<Object>> promiseMap) {
        this.promiseMap = promiseMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRespMessage msg) throws Exception {

        Promise<Object> promise = promiseMap.remove(msg.getSequenceId());

        if (promise == null) {
            log.error("此rpc没有promise来接收响应的结果：{}", msg);
        } else {

            Throwable throwable = msg.getT();

            if (throwable != null) {
                promise.setFailure(throwable);
            } else {
                promise.setSuccess(msg.getResult());
            }

        }

    }
}
